/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* newhead = new ListNode();
        newhead->next = head;
        ListNode* pcur = newhead;
        ListNode* cur = head;
        ListNode* next = nullptr;
        ListNode* nnext = nullptr;
        if(cur)
        {
            next = cur->next;
        }
        if(next)
        {
            nnext = next->next;
        }
        while(cur&&next)
        {
            //进入循环的条件就是保证要交换的两个节点必须存在值
            //交换逻辑首先0 1 2 3 
            next->next = cur;//将2的next修改到1上
            cur->next = nnext;//将1的next修改到3上
            pcur->next = next;//将0的next修改到2上
            //完成逻辑交换
            pcur = cur;//1现在就是下一组交换的哨兵节点
            cur = nnext;//3就是下一次交换的第一个节点
            if(cur)
            {
                next = cur->next;
            }
            else
            {
                break;//剩下的节点不够数量进行交换
            }
            if(next)
            {
                nnext = next->next;//下下一组交换的头节点
            }
            else
            {
                break;
            }
        }
        ListNode* ret = newhead->next;
        delete newhead;
        return ret;
    }
};